<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI 语音实时转文字 - 示例</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            padding: 40px;
            max-width: 600px;
            width: 100%;
        }

        h1 {
            color: #333;
            margin-bottom: 10px;
            text-align: center;
        }

        .subtitle {
            color: #666;
            text-align: center;
            margin-bottom: 30px;
            font-size: 14px;
        }

        .status {
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 20px;
            text-align: center;
            font-weight: 500;
        }

        .status.disconnected {
            background: #fee;
            color: #c33;
        }

        .status.connected {
            background: #efe;
            color: #3c3;
        }

        .status.recording {
            background: #fef3cd;
            color: #856404;
            animation: pulse 1.5s infinite;
        }

        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.7; }
        }

        .controls {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }

        button {
            flex: 1;
            padding: 15px;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }

        button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .btn-connect {
            background: #667eea;
            color: white;
        }

        .btn-connect:hover:not(:disabled) {
            background: #5568d3;
            transform: translateY(-2px);
        }

        .btn-start {
            background: #48bb78;
            color: white;
        }

        .btn-start:hover:not(:disabled) {
            background: #38a169;
            transform: translateY(-2px);
        }

        .btn-stop {
            background: #f56565;
            color: white;
        }

        .btn-stop:hover:not(:disabled) {
            background: #e53e3e;
            transform: translateY(-2px);
        }

        .result-box {
            background: #f7fafc;
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            padding: 20px;
            min-height: 150px;
            margin-bottom: 20px;
        }

        .result-box h3 {
            color: #2d3748;
            margin-bottom: 10px;
            font-size: 16px;
        }

        .result-text {
            color: #4a5568;
            line-height: 1.6;
            white-space: pre-wrap;
            word-wrap: break-word;
        }

        .result-text.empty {
            color: #a0aec0;
            font-style: italic;
        }

        .log-box {
            background: #2d3748;
            color: #e2e8f0;
            border-radius: 10px;
            padding: 15px;
            max-height: 200px;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            font-size: 12px;
        }

        .log-item {
            margin-bottom: 5px;
            padding: 5px;
            border-left: 3px solid #667eea;
            padding-left: 10px;
        }

        .log-item.error {
            border-left-color: #f56565;
        }

        .log-item.success {
            border-left-color: #48bb78;
        }

        .config {
            background: #edf2f7;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
        }

        .config label {
            display: block;
            color: #2d3748;
            margin-bottom: 5px;
            font-weight: 500;
            font-size: 14px;
        }

        .config input, .config select {
            width: 100%;
            padding: 8px;
            border: 1px solid #cbd5e0;
            border-radius: 5px;
            font-size: 14px;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🎤 AI 语音实时转文字</h1>
        <p class="subtitle">基于 WebSocket 的实时语音识别</p>

        <div class="config">
            <label for="wsUrl">WebSocket 地址:</label>
            <input type="text" id="wsUrl" value="ws://localhost:48090/ws" placeholder="ws://localhost:48090/ws">
            
            <label for="language">语言:</label>
            <select id="language">
                <option value="zh">中文</option>
                <option value="en">English</option>
                <option value="auto">自动检测</option>
            </select>
        </div>

        <div id="status" class="status disconnected">
            ⚠️ 未连接
        </div>

        <div class="controls">
            <button id="connectBtn" class="btn-connect">连接</button>
            <button id="startBtn" class="btn-start" disabled>开始录音</button>
            <button id="stopBtn" class="btn-stop" disabled>停止录音</button>
        </div>

        <div class="result-box">
            <h3>识别结果:</h3>
            <div id="resultText" class="result-text empty">等待识别...</div>
        </div>

        <div class="log-box" id="logBox">
            <div class="log-item">系统就绪，请点击"连接"按钮开始...</div>
        </div>
    </div>

    <script>
        let ws = null;
        let mediaRecorder = null;
        let audioChunks = [];
        let isRecording = false;

        const statusEl = document.getElementById('status');
        const connectBtn = document.getElementById('connectBtn');
        const startBtn = document.getElementById('startBtn');
        const stopBtn = document.getElementById('stopBtn');
        const resultText = document.getElementById('resultText');
        const logBox = document.getElementById('logBox');
        const wsUrlInput = document.getElementById('wsUrl');
        const languageSelect = document.getElementById('language');

        // 添加日志
        function addLog(message, type = 'info') {
            const logItem = document.createElement('div');
            logItem.className = `log-item ${type}`;
            logItem.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
            logBox.appendChild(logItem);
            logBox.scrollTop = logBox.scrollHeight;
        }

        // 更新状态
        function updateStatus(status, text) {
            statusEl.className = `status ${status}`;
            statusEl.textContent = text;
        }

        // 连接 WebSocket
        connectBtn.addEventListener('click', () => {
            const wsUrl = wsUrlInput.value.trim();
            if (!wsUrl) {
                alert('请输入 WebSocket 地址');
                return;
            }

            if (ws && ws.readyState === WebSocket.OPEN) {
                // 断开连接
                ws.close();
                return;
            }

            addLog('正在连接 WebSocket...');
            ws = new WebSocket(wsUrl);

            ws.onopen = () => {
                addLog('WebSocket 连接成功', 'success');
                updateStatus('connected', '✅ 已连接');
                connectBtn.textContent = '断开';
                startBtn.disabled = false;
            };

            ws.onmessage = (event) => {
                try {
                    const message = JSON.parse(event.data);
                    addLog(`收到消息: ${message.type}`);

                    if (message.type === 'ai-voice-transcription') {
                        const result = JSON.parse(message.content);
                        
                        if (result.error) {
                            addLog(`错误: ${result.error}`, 'error');
                            resultText.textContent = `错误: ${result.error}`;
                            resultText.className = 'result-text error';
                        } else if (result.text) {
                            addLog(`识别结果: ${result.text}`, 'success');
                            resultText.textContent = result.text;
                            resultText.className = 'result-text';
                        }

                        if (result.finished) {
                            addLog('识别完成', 'success');
                        }
                    }
                } catch (e) {
                    addLog(`消息解析失败: ${e.message}`, 'error');
                }
            };

            ws.onerror = (error) => {
                addLog('WebSocket 错误', 'error');
                console.error('WebSocket error:', error);
            };

            ws.onclose = () => {
                addLog('WebSocket 连接已关闭', 'error');
                updateStatus('disconnected', '⚠️ 未连接');
                connectBtn.textContent = '连接';
                startBtn.disabled = true;
                stopBtn.disabled = true;
                isRecording = false;
            };
        });

        // 开始录音
        startBtn.addEventListener('click', async () => {
            if (isRecording) return;

            try {
                addLog('请求麦克风权限...');
                const stream = await navigator.mediaDevices.getUserMedia({ 
                    audio: {
                        echoCancellation: true,
                        noiseSuppression: true,
                        sampleRate: 16000
                    } 
                });

                addLog('麦克风权限已获取', 'success');

                // 发送开始消息
                const startMessage = {
                    type: 'ai-voice-transcription',
                    content: JSON.stringify({
                        type: 'start',
                        format: 'webm',
                        language: languageSelect.value
                    })
                };
                ws.send(JSON.stringify(startMessage));
                addLog('已发送开始录音消息', 'success');

                // 创建录音器
                mediaRecorder = new MediaRecorder(stream, {
                    mimeType: 'audio/webm;codecs=opus'
                });

                audioChunks = [];

                mediaRecorder.ondataavailable = (event) => {
                    if (event.data.size > 0) {
                        audioChunks.push(event.data);
                        addLog(`音频数据块: ${event.data.size} bytes`);
                    }
                };

                mediaRecorder.onstop = () => {
                    addLog('录音已停止，处理音频数据...');
                    const audioBlob = new Blob(audioChunks, { type: 'audio/webm' });
                    
                    const reader = new FileReader();
                    reader.readAsDataURL(audioBlob);
                    reader.onloadend = () => {
                        const base64data = reader.result;
                        addLog(`音频数据大小: ${Math.round(base64data.length / 1024)} KB`);

                        // 发送音频数据
                        const audioMessage = {
                            type: 'ai-voice-transcription',
                            content: JSON.stringify({
                                type: 'audio',
                                data: base64data,
                                format: 'webm',
                                language: languageSelect.value
                            })
                        };
                        ws.send(JSON.stringify(audioMessage));
                        addLog('已发送音频数据', 'success');

                        // 发送停止消息
                        const stopMessage = {
                            type: 'ai-voice-transcription',
                            content: JSON.stringify({
                                type: 'stop'
                            })
                        };
                        ws.send(JSON.stringify(stopMessage));
                        addLog('已发送停止消息，等待识别结果...');
                    };

                    // 停止所有音频轨道
                    stream.getTracks().forEach(track => track.stop());
                };

                mediaRecorder.start();
                isRecording = true;
                updateStatus('recording', '🎙️ 录音中...');
                startBtn.disabled = true;
                stopBtn.disabled = false;
                addLog('录音已开始', 'success');

            } catch (error) {
                addLog(`麦克风权限被拒绝或出错: ${error.message}`, 'error');
                alert('无法访问麦克风，请检查浏览器权限设置');
            }
        });

        // 停止录音
        stopBtn.addEventListener('click', () => {
            if (!isRecording || !mediaRecorder) return;

            mediaRecorder.stop();
            isRecording = false;
            updateStatus('connected', '✅ 已连接');
            startBtn.disabled = false;
            stopBtn.disabled = true;
            addLog('正在停止录音...');
        });
    </script>
</body>
</html>





